/********************************************************************************
* Description: tcp connection object, process user data
* Author: hsqiang
* Create Date: 2023-06-22
********************************************************************************/
#ifndef CONNECTION_HPP_
#define CONNECTION_HPP_

#include "noncopyable.hpp"
#include "channel.hpp"
#include "event_callback.hpp"
#include "assert_define.hpp"
#include <memory>
#include <map>

namespace event_framework
{
    class EventLoop;
    class Connection : Noncopyable
    {
    public:
        Connection(EventLoop& loop, Socket& socket_) : socket(socket_)
        {
            channel = std::make_shared<Channel>(loop, socket.GetFd());
            ASSERT(channel != nullptr);
        }
        ~Connection() = default;

        void Open(const EventCallback& callback);
        void Close()
        {
            channel->DisableAll();
            socket.Close();
        }
    private:
        Socket socket;
        ChannelPtr channel;
    };
    using ConnectionPtr = std::shared_ptr<Connection>;

    class ConnectionMgr final : Noncopyable
    {
    public:
        ConnectionMgr() = default;
        ~ConnectionMgr() = default;
        ConnectionPtr GetConnection(int fd);
        void AddConnection(int fd, ConnectionPtr conn)
        {
            ASSERT(connMap.count(fd) == 0);
            connMap[fd] = conn;
        }
        bool HasConnection(int fd)
        {
            return connMap.count(fd) > 0;
        }
        void CloseConnection(int fd);
        void CloseAll();
    private:
        std::map<int, ConnectionPtr> connMap;
    };
}

#endif